<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header" style="display: flex; justify-content: space-between; align-items: center;">
        <div style="display: flex; align-items: center; gap: 10px;">
          <el-input 
            v-model="queryAdminId" 
            style="width: 240px" 
            placeholder="请输入管理员ID（留空则显示当前管理员日志）" 
            clearable
          />
          <el-select v-model="queryOperationType" placeholder="请选择操作类型" style="width: 240px">
            <el-option label="全部" value="" />
            <el-option v-for="type in operationTypes" :key="type" :label="type" :value="type" />
          </el-select>
          <el-button class="button" type="primary" @click="queryLogs">查询</el-button>
          <el-button class="button" type="info" @click="showMyLogs">查看我的日志</el-button>
        </div>
        <div>
          <el-button class="button" type="danger" @click="deleteSelectedLogs" :disabled="!multipleSelection.length">批量删除</el-button>
        </div>
      </div>
    </template>
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="admin-info-card">
          <template #header>
            <div class="clearfix">
              <span><strong>管理员信息</strong></span>
            </div>
          </template>
          <div class="admin-info-container">
            <!-- 添加头像区域 -->
            <div class="admin-avatar">
              <img 
                :src="selectedAdmin.avatar || defaultAvatar" 
                alt="管理员头像"
              >
            </div>
            
            <!-- 美化后的信息展示 -->
            <div class="admin-info-content">
              <div class="admin-info-section">
                <div class="info-item">
                  <span class="label">管理员ID:</span>
                  <span class="value">{{ selectedAdmin.adminId || '未提供' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">用户名:</span>
                  <span class="value">{{ selectedAdmin.username || '未提供' }}</span>
                </div>
              </div>
              <div class="admin-info-section">
                <div class="info-item">
                  <span class="label">真实姓名:</span>
                  <span class="value">{{ selectedAdmin.realName || '未提供' }}</span>
                </div>
                <div class="info-item">
                  <span class="label">角色:</span>
                  <span class="value">{{ selectedAdmin.role || '未提供' }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card>
          <el-table 
            :data="logTableData" 
            style="width: 100%" 
            border 
            stripe 
            v-loading="loading"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column prop="logId" label="日志ID" width="120" align="center" />
            <el-table-column prop="operationType" label="操作类型" width="150" align="center" />
            <el-table-column prop="operationDetail" label="操作详情" min-width="300" show-overflow-tooltip />
            <el-table-column prop="createTime" label="操作时间" width="150" align="center" :formatter="formatTableDate" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </el-card>
</template>

<script>
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '../../store/UserStore'

export default {
  data() {
    return {
      queryAdminId: "", 
      queryOperationType: "", 
      operationTypes: [], 
      logTableData: [], 
      selectedAdmin: {
        adminId: '',
        username: '',
        realName: '',
        role: '',
        avatar: ''
      },
      defaultAvatar: "/images/default-avatar.png",
      avatarBasePath: "/avatars/",
      supportedImageFormats: ['.jpg', '.jpeg', '.png', '.gif'],
      multipleSelection: [],
      loading: false
    };
  },
  methods: {
    // 获取操作类型列表
    fetchOperationTypes() {
      console.log('开始获取操作类型列表');
      this.$http.get("http://localhost:8080/adminLogs/operationTypes")
        .then(response => {
          console.log('获取操作类型响应:', response);
          if (Array.isArray(response.data)) {
            this.operationTypes = response.data;
            console.log('更新后的操作类型列表:', this.operationTypes);
          } else {
            console.error('操作类型数据格式不正确:', response.data);
            this.$message.error('获取操作类型数据格式不正确');
            this.operationTypes = [];
          }
        })
        .catch(error => {
          console.error('获取操作类型失败:', error);
          this.$message.error("获取操作类型失败");
          this.operationTypes = [];
        });
    },
    // 获取管理员信息
    async fetchAdminInfo() {
      try {
        console.log('开始获取管理员信息...')
        const userStore = useUserStore()
        
        // 如果指定了查询的管理员ID，则获取该管理员的详细信息
        if (this.queryAdminId) {
          const response = await this.$http.get(`http://localhost:8080/admin_user_vo/detail/${this.queryAdminId}`);
          console.log('获取指定管理员信息响应:', response);
          
          if (response.data) {
            const adminInfo = response.data;
            console.log('找到查询的管理员信息:', adminInfo);
            this.selectedAdmin = {
              adminId: adminInfo.adminId,
              username: adminInfo.username,
              role: adminInfo.role,
              realName: adminInfo.realName || '未知姓名',
              avatar: this.getAvatarUrl(adminInfo.avatar)
            }
          } else {
            ElMessage.warning('未找到指定的管理员信息');
            this.selectedAdmin = {
              adminId: this.queryAdminId,
              username: '未知管理员',
              role: '未知角色',
              realName: '未知姓名',
              avatar: this.defaultAvatar
            }
          }
        } else {
          // 如果没有指定查询ID，则获取所有管理员信息并找到当前登录的管理员
          const response = await this.$http.get('http://localhost:8080/admin_user_vo/list');
          console.log('获取管理员列表响应:', response);

          if (response.data && Array.isArray(response.data)) {
            const currentAdminInfo = response.data.find(admin => admin.userId === userStore.userInfo.userId);
            if (currentAdminInfo) {
              console.log('找到当前管理员信息:', currentAdminInfo);
              this.selectedAdmin = {
                adminId: currentAdminInfo.adminId,
                username: currentAdminInfo.username,
                role: currentAdminInfo.role,
                realName: currentAdminInfo.realName || '未知姓名',
                avatar: this.getAvatarUrl(currentAdminInfo.avatar)
              }
            } else {
              console.warn('未找到当前管理员信息，使用用户信息');
              this.selectedAdmin = {
                adminId: userStore.userInfo.userId,
                username: userStore.userInfo.username,
                role: userStore.userInfo.role,
                realName: userStore.userInfo.realName || '未知姓名',
                avatar: this.getAvatarUrl(userStore.userInfo.avatar)
              }
            }
          } else {
            throw new Error('获取管理员列表失败')
          }
        }
        
        console.log('处理后的管理员信息:', this.selectedAdmin)
      } catch (error) {
        console.error('获取管理员信息失败:', error)
        ElMessage.error('获取管理员信息失败')
        this.selectedAdmin = {
          adminId: '未知',
          username: '未知管理员',
          role: '未知角色',
          realName: '未知姓名',
          avatar: this.defaultAvatar
        }
      }
    },
    // 获取管理员日志
    async fetchLogs() {
      this.loading = true;
      const userStore = useUserStore();

      try {
        // 如果没有输入管理员ID，则使用当前管理员ID
        const targetAdminId = this.queryAdminId || this.selectedAdmin.adminId;
        
        if (!targetAdminId) {
          ElMessage.error('未获取到管理员信息');
          this.loading = false;
          return;
        }

        console.log('开始获取日志数据，管理员ID:', targetAdminId);

        // 获取日志数据
        const params = {
          adminId: parseInt(targetAdminId),
          operationType: this.queryOperationType || null
        };

        const logsResponse = await this.$http.get("http://localhost:8080/adminLogs/search", { params });
        console.log('获取日志数据响应:', logsResponse);

        if (Array.isArray(logsResponse.data)) {
          this.logTableData = logsResponse.data;
        } else {
          console.error('日志数据格式不正确:', logsResponse.data);
          ElMessage.error('获取日志数据格式不正确');
          this.logTableData = [];
        }
      } catch (error) {
        console.error('获取数据失败:', error);
        ElMessage.error('获取数据失败');
        this.logTableData = [];
      } finally {
        this.loading = false;
      }
    },
    // 查询日志
    async queryLogs() {
      console.log('触发查询操作');
      await this.fetchAdminInfo(); // 先获取管理员信息
      await this.fetchLogs(); // 再获取日志
    },
    // 导出日志
    exportLogs() {
      if (!this.queryAdminId) {
        this.$message.warning('请输入管理员ID');
        return;
      }

      const params = {
        adminId: parseInt(this.queryAdminId),
        operationType: this.queryOperationType || null
      };
      
      window.location.href = `http://localhost:8080/adminLogs/export?adminId=${params.adminId}&operationType=${params.operationType || ''}`;
    },
    // 格式化日期
    formatTableDate(row, column, cellValue) {
      if (!cellValue) return "";
      const date = new Date(cellValue);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },
    // 处理头像路径
    getAvatarUrl(avatar) {
      try {
        console.log('处理头像路径，原始路径:', avatar);
        
        if (!avatar) {
          console.log('头像为空，使用默认头像');
          return this.defaultAvatar;
        }
        
        // 如果头像路径是完整的URL，直接返回
        if (avatar.startsWith('http://') || avatar.startsWith('https://')) {
          console.log('检测到网络头像URL:', avatar);
          return avatar;
        }
        
        // 如果是本地头像，使用相对路径
        // 移除开头的斜杠，避免重复
        const cleanAvatar = avatar.startsWith('/') ? avatar.substring(1) : avatar;
        console.log('清理后的头像路径:', cleanAvatar);
        
        // 检查文件格式
        const hasValidExtension = this.supportedImageFormats.some(format => 
          cleanAvatar.toLowerCase().endsWith(format)
        );
        console.log('是否包含有效扩展名:', hasValidExtension);
        
        // 如果路径已经包含 avatars 目录
        if (cleanAvatar.startsWith('avatars/')) {
          const fullPath = `/${cleanAvatar}`;
          console.log('处理后的头像路径(包含avatars目录):', fullPath);
          return fullPath;
        }
        
        // 如果没有有效的文件扩展名，添加默认扩展名
        const avatarWithExtension = hasValidExtension ? cleanAvatar : `${cleanAvatar}.jpg`;
        const fullPath = `${this.avatarBasePath}${avatarWithExtension}`;
        console.log('最终处理后的头像路径:', fullPath);
        return fullPath;
      } catch (error) {
        console.error('处理头像路径时出错:', error);
        return this.defaultAvatar;
      }
    },
    // 选中行变化时的处理
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 批量删除选中的日志
    deleteSelectedLogs() {
      const logIds = this.multipleSelection.map(item => item.logId);
      this.$confirm(`确认删除选中的${logIds.length}条日志吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return Promise.all(logIds.map(id => axios.delete(`http://localhost:8080/adminLogs/delete/${id}`)));
      }).then(() => {
        this.$message.success(`成功删除${logIds.length}条日志`);
        this.fetchLogs();
        this.multipleSelection = [];
      }).catch(error => {
        if (error !== 'cancel' && error !== 'close') {
          console.error('批量删除失败:', error);
          this.$message.error("批量删除失败");
        }
      });
    },
    // 显示当前管理员的日志
    async showMyLogs() {
      this.queryAdminId = '';
      await this.fetchAdminInfo();
      await this.fetchLogs();
    }
  },
  mounted() {
    this.fetchOperationTypes();
    // 默认显示当前管理员的日志
    this.showMyLogs();
  }
};
</script>

<style scoped>
.box-card {
  margin: 20px;
}
.admin-info-card {
  margin-bottom: 20px;
}
.clearfix {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 新增的美化样式 */
.admin-info-container {
  display: flex;
  align-items: center;
  padding: 15px;
}

.admin-avatar {
  width: 100px;
  height: 100px;
  margin-right: 30px;
  flex-shrink: 0;
}

.admin-avatar img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #f0f0f0;
}

.admin-info-content {
  display: flex;
  flex-grow: 1;
  justify-content: space-between;
  flex-wrap: wrap;
}

.admin-info-section {
  flex: 1;
  min-width: 200px;
  margin: 0 10px;
}

.info-item {
  margin: 8px 0;
  display: flex;
  align-items: center;
}

.label {
  min-width: 80px;
  color: #666;
  font-weight: bold;
  margin-right: 10px;
}

.value {
  color: #333;
  flex: 1;
}
</style>